package com.project.base.common;


import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.util.Date;
import java.util.Properties;

/**
 * @author caoyong
 * @version 1.0.0
 * @since 2017-12-18 11:07
 **/
public class SendMailUtil1 {
    public static boolean sendMail(SendMailVO sendMailVO) {
        boolean isFlag;
        try {
            String smtpFromMail = "basic_service@lvmama.com";  //账号
            String pwd = "BasicService123!"; //密码
            int port = 25; //端口
            String host = "smtp.exmail.qq.com"; //发件服务器

            Properties props = new Properties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth", "true");
            Session session = Session.getDefaultInstance(props);
            session.setDebug(false);

            MimeMessage message = new MimeMessage(session);
            try {
                InternetAddress[] internetAddressTo = InternetAddress.parse(sendMailVO.getToMail());
                message.setFrom(new InternetAddress(smtpFromMail, MimeUtility.encodeText("智能数据部", "UTF-8", "B")));
                message.addRecipients(Message.RecipientType.TO, internetAddressTo);
                message.setSubject(MimeUtility.encodeText(sendMailVO.getSubject(), "UTF-8", "B"));
                message.addHeader("charset", "UTF-8");

                /*添加正文内容*/
                Multipart multipart = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
                contentPart.setContent(sendMailVO.getContent(), "text/html; charset=utf-8");
                //contentPart.setText(sendMailVO.getContent());
                multipart.addBodyPart(contentPart);

                /*添加附件*/
                MimeBodyPart fileBody = new MimeBodyPart();
                DataSource source = new ByteArrayDataSource(sendMailVO.getInputStream(), "application/msexcel");
                fileBody.setDataHandler(new DataHandler(source));
                String fileName = sendMailVO.getFilename() + ".xls";
                // 中文乱码问题
                fileBody.setFileName(MimeUtility.encodeText(fileName, "UTF-8", "B"));
                multipart.addBodyPart(fileBody);

                message.setContent(multipart);
                message.setSentDate(new Date());
                message.saveChanges();
                Transport transport = session.getTransport("smtp");

                transport.connect(host, port, smtpFromMail, pwd);
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                isFlag = true;
            } catch (Exception e) {
                isFlag = false;
            }
        } catch (Exception e) {
            isFlag = false;
        }
        return isFlag;
    }
}
